package com.cloudeasy.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.user.mapper.PermissionMapper;
import com.cloudeasy.user.po.Permission;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Transactional(rollbackFor = Exception.class)
public class PermissionService extends ServiceImpl<PermissionMapper, Permission> {

    /**
     * 根据Id查询权限
     *
     * @param permissionIds Id列表
     * @return {@link List<Permission>}
     */
    public List<Permission> list(List<String> permissionIds) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", permissionIds);
        return this.list(queryWrapper);
    }

    /**
     * 获取等同作用的权限Id列表
     *
     * @param permissionId 权限Id
     * @return {@link List<Permission>}
     */
    public List<Permission> findSamePermissions(String permissionId) {
        Permission permission = this.getById(permissionId);
        if (permission == null) {
            throw new CloudEasyException(ResultCodeEnum.ID_NOT_EXISTS);
        }
        List<Permission> ids = new ArrayList<>();
        ids.add(permission);
        while (permission.getParentId() != null) {
            permission = this.getById(permission.getParentId());
            ids.add(permission);
        }
        return ids;
    }
}
